<?php

namespace app\command;

use app\logic\es\fp\EsPost;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;


class EsPostCommand extends Command
{
    // 执行导入动态到es的操作
    protected function configure()
    {
        $this->setName('esPost')
            ->addArgument('type', Argument::OPTIONAL, "function", "syncFriendList")
            ->addOption('id', '', Option::VALUE_OPTIONAL, "{uid}_{post_id}")
            ->setDescription('Es 动态导入');
    }

    protected function execute(Input $input, Output $output)
    {
        $t1 = microtime(true);
        $type = trim($input->getArgument('type'));

        switch ($type) {
            case 'deleteIndex':
                EsPost::getInstance()->deleteIndex();
                break;
            case 'import':
                if ($input->hasOption('id')) {
                    $uids = trim($input->getOption('id'));
                    if (!empty($uids)) {
                        if ($uids == "all") {
                            EsPost::getInstance()->importAll();
                        } else {
                            $uids = explode(',', trim($input->getOption('id')));
                            foreach ($uids as $v) {
                                list($uid, $postId) = explode('_', $v);
                                EsPost::getInstance()->import(['user_id'=>$uid, 'post_id'=>$postId]);
                            }
                        }
                    }
                } else {
                    $output->writeln("请输入uid");
                    return;
                }
                break;
            case 'initIndexSetting':
                $esUser = EsPost::getInstance();
                if ($esUser->indexExists()) {
                    EsPost::getInstance()->deleteIndex();
                }
                $res = EsPost::getInstance()->initIndexSetting();
                if ($res->asArray()) {
                    EsPost::getInstance()->importAll();
                    $output->writeln("初始化成功".json_encode($res->asArray()));
                } else {
                    $output->writeln("初始化失败");
                }
                break;
            default:
                $output->writeln("请输入正确的参数");
                return;
        }
        $t2 = microtime(true);
        $output->writeln("执行完毕,耗时: " . ($t2 - $t1) . "秒");
    }
}
